﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using Service.common;
using Service.utils;
using System.Data;
using Service.enums;

namespace Service.service.impl
{
    public class GetGhsjImpl : IGetGhsj
    {
        private string result;

        #region 更新
        public string update(string json)
        {
            try
            {
                var mJObj = JArray.Parse(json);
                //将单条记录取出操作
                foreach (var jsonlist in mJObj)
                {
                    string jsons = jsonlist.ToString();
                    //反序列化json
                    JObject jo = JsonConvert.DeserializeObject(jsons) as JObject;
                    //声明更新用的sql
                    StringBuilder sql = new StringBuilder();
                    JToken jtk;
                    StringBuilder sqlmy = new StringBuilder(@"SELECT * FROM boat_safeinfo");
                    //dt2为船表数据
                    DataTable dt2 = ResultUtil.getDataTable(sqlmy.ToString());
                    //以船名为主键
                    if (jo.TryGetValue("bs_boatname", out jtk))
                    {
                        string bn = jtk.ToString();
                        DataRow[] dtr = dt2.Select("bs_boatname='" + bn + "'");
                        //如果船存在则更新这条记录
                        if (dtr.Length == 1)
                        {
                            //sql="";
                            sql.Append(string.Format(@"update boat_safeinfo set "));
                            foreach (KeyValuePair<string, JToken> kyp in jo)
                            {
                                //利用键名相等写入sql
                                foreach (DataColumn dc in dt2.Columns)
                                {
                                    //判断键名相等且值不为空
                                    if (kyp.Key.Equals(dc.ColumnName) && !string.IsNullOrEmpty(kyp.Value.ToString()))
                                    {
                                        sql.Append(string.Format(@"{0}={1},", kyp.Key, string.Format(@"'{0}'", kyp.Value)));
                                    }
                                }
                            }
                            string sqls = sql.ToString();
                            string sqlsnew = sqls.Remove(sqls.Length - 1);
                            sqlsnew = sqlsnew + " where bs_boatname='" + jtk + "';";
                            //执行sql
                            int re = ResultUtil.insOrUpdOrDel(sqlsnew);
                            result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                        }
                        //如果船不存在则插入一条记录
                        else {
                            sql.Append(string.Format(@"insert into boat_safeinfo set "));
                            foreach (KeyValuePair<string, JToken> kyp in jo)
                            {
                                foreach (DataColumn dc in dt2.Columns)
                                {
                                    if (kyp.Key.Equals(dc.ColumnName) && !string.IsNullOrEmpty(kyp.Value.ToString()))
                                    {
                                        sql.Append(string.Format(@"{0}={1},", kyp.Key, string.Format(@"'{0}'", kyp.Value)));
                                    }
                                }
                            }
                            string sqls = sql.ToString();
                            string sqlsnew = sqls.Remove(sqls.Length - 1);
                            //执行sql
                            int re = ResultUtil.insOrUpdOrDel(sqlsnew);
                            result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                        }
                        string sql3 = string.Format(@"select bu_phone from boat_userinfo");
                        DataTable dt3 = ResultUtil.getDataTable(sql3);
                        foreach (KeyValuePair<string, JToken> kyp in jo)
                        {
                            string str = kyp.Key.ToString();
                            if (str.Contains("telbu_p0"))
                            {
                                DataRow[] dtr2 = dt3.Select("bu_phone='" + jo["telbu_p0"].ToString() + "'");
                                if (dtr2.Length == 0)
                                {
                                    string sqlthis = string.Format(@"insert into boat_userinfo set bu_phone='" + jo["telbu_p0"].ToString() + "',bu_username='" + jo["telbu_p0"].ToString() + "',bu_name='" + jo["bu_p0"].ToString() + "',permissions=0;");
                                    int re = ResultUtil.insOrUpdOrDel(sqlthis);
                                    result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(jo["telbu_p0"].ToString()) && !string.IsNullOrEmpty(jo["bu_p0"].ToString()))
                                    {
                                        string sqlthis = string.Format(@"update boat_userinfo set bu_phone='" + jo["telbu_p0"].ToString() + "',bu_username='" + jo["telbu_p0"].ToString() + "',bu_name='" + jo["bu_p0"].ToString() + "',permissions=0 where bu_phone='" + jo["telbu_p0"].ToString() + "';");
                                        int re = ResultUtil.insOrUpdOrDel(sqlthis);
                                        result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                                    }
                                }

                            }
                            else if (str.Contains("telbu_p1"))
                            {
                                DataRow[] dtr3 = dt3.Select("bu_phone='" + jo[str].ToString() + "'");
                                if (dtr3.Length == 0)
                                {
                                    string sqlsnew = str.Remove(0, 3);
                                    string sqlthis = string.Format(@"insert into boat_userinfo set bu_phone='" + jo[str].ToString() + "',bu_username='" + jo[str].ToString() + "',bu_name='" + jo[sqlsnew].ToString() + "',permissions=1;");
                                    int re = ResultUtil.insOrUpdOrDel(sqlthis);
                                    result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(jo["telbu_p0"].ToString()) && !string.IsNullOrEmpty(jo["bu_p0"].ToString()))
                                    {
                                        string sqlsnew = str.Remove(0, 3);
                                        string sqlthis = string.Format(@"update boat_userinfo set bu_phone='" + jo[str].ToString() + "',bu_username='" + jo[str].ToString() + "',bu_name='" + jo[sqlsnew].ToString() + "',permissions=1  where bu_phone='" + jo[str].ToString() + "';");
                                        int re = ResultUtil.insOrUpdOrDel(sqlthis);
                                        result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                                    }
                                }
                            }
                        }
                    }
                }
                updatecard(json);
            }
            catch (Exception e)
            {
                result = ResultUtil.getStandardResult((int)Status.Error, EnumUtil.getMessageStr((int)Message.UpdateFailure), e.Message);
            }
            return result;
        }
        #endregion

        #region 北斗卡号
        public string updatecard(string json)
        {
            try
            {
                var mJObj = JArray.Parse(json);
                foreach (var jsonlist in mJObj)
                {
                    //反序列化json
                    string jsons = jsonlist.ToString();
                    JObject jo = JsonConvert.DeserializeObject(jsons) as JObject;
                    //声明更新用的sql
                    StringBuilder sql = new StringBuilder();
                    //尝试获取id
                    JToken jtk;
                    StringBuilder sqlmy = new StringBuilder(@"SELECT * FROM boat_terminfo");
                    //查询所有字段的字段名
                    DataTable dt2 = ResultUtil.getDataTable(sqlmy.ToString());
                    if (jo.TryGetValue("bt_terminal_code", out jtk))
                    {
                        string sql2 = string.Format(@"select bt_terminal_code from boat_terminfo");
                        DataTable dt = ResultUtil.getDataTable(sql2);
                        int bsid;
                        string bn = jtk.ToString();
                        DataRow[] dtr = dt.Select("bt_terminal_code='" + bn + "'");
                        DataTable dt3;
                        string sql3;
                        if (dtr.Length == 1)
                        {
                            int re;
                            sql3 = string.Format(@"select bs_id from boat_safeinfo where {0}={1};", "bs_boatname", string.Format(@"'{0}'", jo["bs_boatname"]));
                            dt3 = ResultUtil.getDataTable(sql3);
                            bsid = int.Parse(dt3.Rows[0][0].ToString());
                            sql.Append(string.Format(@"update boat_terminfo set bs_id={0} where bt_terminal_code='{1}';", bsid, bn));
                            string sqls = sql.ToString();
                            //执行sql
                            re = ResultUtil.insOrUpdOrDel(sqls);
                            result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,effect" + re + "datas;");
                        }
                        else {
                            int re;
                            sql3 = string.Format(@"select bs_id,bs_boatname from boat_safeinfo where {0}={1};", "bs_boatname", string.Format(@"'{0}'", jo["bs_boatname"]));
                            dt3 = ResultUtil.getDataTable(sql3);
                            bsid = int.Parse(dt3.Rows[0][0].ToString());
                            sql.Append(string.Format(@"insert into boat_terminfo set bs_id={0},bt_terminal_code='{1}';", bsid, bn));
                            string sqls = sql.ToString();
                            //执行sql
                            re = ResultUtil.insOrUpdOrDel(sqls);
                            result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Insert), @"success,effect" + re + "datas;");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                result = ResultUtil.getStandardResult((int)Status.Error, EnumUtil.getMessageStr((int)Message.UpdateFailure), e.Message);
            }
            return result;
        }
        #endregion

    }
}